#include "NetworkMessage.h"

NetworkMessage::NetworkMessage(uint8* header_data)
    : _data(NULL), _type(NONE), _body_length(0) 
{
    DecodeHeader(header_data); 
}

NetworkMessage::NetworkMessage(msg_t type, size_t body_length)
    : _data(NULL), _type(type), _body_length(body_length) 
{
    _data = new uint8[GetLength()];
    
    EncodeHeader();
}

size_t NetworkMessage::GetLength() const
{
    return _body_length + HEADER_LENGTH;
}

size_t NetworkMessage::GetHeaderLength()
{
    return HEADER_LENGTH;
}

size_t NetworkMessage::GetBodyLength() const
{
    return _body_length;
}

msg_t NetworkMessage::GetType() const
{
    return _type;
}

const uint8* NetworkMessage::GetData() const
{
    return _data;
}

uint8* NetworkMessage::GetHeader()
{
    return _data;
}

uint8* NetworkMessage::GetBody()
{
    return _data + HEADER_LENGTH;
}

void NetworkMessage::EncodeBody(const uint8* body_data)
{
    memcpy(_data+HEADER_LENGTH,body_data,GetBodyLength());
}

void NetworkMessage::DecodeHeader(uint8* header_data)
{
    _body_length = (size_t) *header_data;
    
    _type = (msg_t) *(header_data + sizeof(size_t));
    
    _data = new uint8[GetLength()];
    
    EncodeHeader();
}

void NetworkMessage::EncodeHeader()
{
    memcpy(_data,&_body_length,sizeof(size_t));
    
    memcpy(_data + sizeof(size_t),&_type,sizeof(msg_t));
}

